<?php


namespace App\Console\Commands;

use App\Models\CommissionLog;
use App\Models\MiyouDaily;
use App\Models\MiyouUser;
use App\Models\Users;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class CompareMobile extends Command
{
    /**
     * 命令行执行命令
     * @var string
     */
    protected $signature = 'compare:mobile';

    /**
     * 命令描述
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $miyouList = MiyouUser::query()->where("state", 0)->whereRaw('hide_mobile is not null')
            ->select(['id', 'hide_mobile'])->get()->toArray();
        $mobileMap = array_count_values(array_column($miyouList, 'hide_mobile'));
        foreach ($miyouList as $miyou) {
            $hideMobile = $miyou['hide_mobile'];
            if($mobileMap[$hideMobile] > 1) {
                MiyouUser::query()->where('id', $miyou['id'])->update(['state' => 2]);
                continue;
            }
            $pre = substr($hideMobile, 0, 3);
            $suf = substr($hideMobile, -4);
            $sql = "SELECT u.mobile FROM users u LEFT JOIN miyou_user mu on u.mobile = mu.mobile " .
                "WHERE left(u.mobile, 3)='{$pre}' AND right(u.mobile, 4)='{$suf}' AND mu.mobile is null";
            $res = DB::select($sql);
            $rowCount = count($res);
            if(empty($rowCount)) {
                continue;
            }
            if($rowCount > 1) {
                MiyouUser::query()->where('id', $miyou['id'])->update(['state' => 2]);
                continue;
            }
            MiyouUser::query()->where('id', $miyou['id'])->update([
                'mobile' => $res[0]->mobile,
                'state' => 1
            ]);
        }
        return true;
    }



}